//
//  CommentController.m
//  quickLook
//
//  Created by J on 15/9/1.
//  Copyright (c) 2015年 JZJ. All rights reserved.
//

#import "CommentController.h"
#import "Header.h"
#import "LandController.h"
#import "CommentCell.h"
#import "UMSocial.h"

@interface CommentController ()<UITextViewDelegate,UITableViewDelegate,UITableViewDataSource>
{

    NSInteger _number;

    BOOL _isLoad;

}

@property(nonatomic,strong)UIToolbar * toolBar;

@property(nonatomic,assign)BOOL isLoad;


@property(nonatomic,strong)UITextView* textView;

@property(nonatomic,strong)UISegmentedControl* segmentedControl;

@property(nonatomic,strong)NSArray* tempArray;

@property(nonatomic,strong)UIButton* sendButton;

@end

@implementation CommentController



- (void)dealloc {
    
    
    [_textView removeObserver:self forKeyPath:@"text"];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    

}

- (void)viewDidLoad {
    [super viewDidLoad];
       [self createUI];
    [self loadLatestData];

    _number=0;
    
    _dataArray=[[NSMutableArray alloc]init];
    _isLoad=NO;
    
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

    
}






- (void)loadLatestData
{

    
    //最新
    
    [DownLoad getLatestCommentWithPageNumber:_number andID:_model.id withBlock:^(NSDictionary* dic, NSError *error) {
        
        
        
        if (_number==0) {
            //下拉刷新
            _dataArray=[NSMutableArray array];
            
            [_tableView.header endRefreshing];
        }else{
            [_tableView.footer endRefreshing];
        }

        
    
        _tempArray=[NSMutableArray arrayWithArray:dic[@"data"][@"comments"]];

        [self getData];

    }];
    //最热
    
    
    



}


- (void)getData{
    
    
    
    
    
    [_tempArray enumerateObjectsUsingBlock:^(NSDictionary* valueDic, NSUInteger idx, BOOL *stop) {
        
        
        Model* model=[[Model alloc]init];
        
        [model setValuesForKeysWithDictionary:valueDic];
        
        
        
        
        [_dataArray addObject:model];
        
        
        
        
    }];
    
    [_tableView reloadData];
    _isLoad=NO;//这是一个异步执行方法 当这个异步操作执行完毕之后 isLoad才会变成NO
    
    




}
- (void)loadHotData
{

    

    [DownLoad getHotCommentWithPageNumber:_number andID:_model.id withBlock:^(NSDictionary* dic, NSError *error) {
        
        
        
        
        if (_number==0) {
            
            
            //下拉刷新
            _dataArray=[NSMutableArray array];
            
            [_tableView.header endRefreshing];
        }else{
            [_tableView.footer endRefreshing];
        }
        

        
        _tempArray=[NSMutableArray arrayWithArray:dic[@"data"][@"comments"]];
        
        
        [self getData];
    }];




}

- (void)createUI {

    
    UINavigationBar *bar=[[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 64)];
    
    [self.view addSubview:bar];

//    UIImage* image=[UIImage imageNamed:@"backbuttonX.png"];
//
//    UIImage* image2= [[image TransformtoSize:CGSizeMake(15, 15)]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    


    
    self.automaticallyAdjustsScrollViewInsets=NO;

    self.view.backgroundColor=[UIColor whiteColor];

    
    _segmentedControl= [[UISegmentedControl alloc]initWithItems:@[@"最新评论",@"最热评论"]];
    
    
    
    //
    _segmentedControl.tintColor= [UIColor grayColor];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,  [UIFont fontWithName:@"" size:16.f],NSFontAttributeName ,[UIColor whiteColor],NSShadowAttributeName ,nil];
    
    
    [_segmentedControl setTitleTextAttributes:dic forState:UIControlStateSelected];
   
    
//    _segmentedControl.center=bar.center;

    _segmentedControl.frame = CGRectMake((bar.frame.size.width - 200)/2.0, (44 - 30)/2.0 + 20,200, 30);
    
    
    
    
    [bar addSubview:_segmentedControl];
    
    [self.view bringSubviewToFront:bar];
    
    
    [_segmentedControl addTarget:self action:@selector(segmentControlValueChanged:) forControlEvents:UIControlEventValueChanged];
    
    NSMutableArray *itemts=[NSMutableArray array];//mutableCopy需要release  (id)mutableCopy;
    _segmentedControl.selectedSegmentIndex=0;//设置默认选中的按钮  index 从左向右

    
    UIImage * leftImage=[[[UIImage imageNamed:@"backbuttonX"]TransformtoSize:CGSizeMake(20, 20)]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
   
    
    
    //添加左侧button
    UIButton * button=[UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat buttonW = 20;
    CGFloat buttonH = 20;
    CGFloat buttonX = 10;
    CGFloat buttonY=(bar.frame.size.height -20 - buttonH)/2.0 + 20;
    button.frame= CGRectMake(buttonX,buttonY, buttonW, buttonH);
    [button setBackgroundImage:leftImage forState:UIControlStateNormal];
    
    [button addTarget:self action:@selector(dismiss:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view bringSubviewToFront:button];

    [bar addSubview:button];
    //创建一个工具栏对象 只有这个controller有 其他没有
    _toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-44, SCREEN_WIDTH, 44)];
    
    _textView=[[UITextView alloc]initWithFrame:CGRectMake(5, 5, SCREEN_WIDTH-50, 34)];
    
    
    _textView.delegate=self;
    _textView.textColor=JZJLIGHTGRAY;
    _textView.text = @"吐槽神马的尽管来";
    
    [_toolBar insertSubview:_textView atIndex:0];
    
    
    
    //发送评论按钮
    _sendButton=[UIButton buttonWithType:UIButtonTypeCustom];
    _sendButton.frame=CGRectMake(SCREEN_WIDTH-40,5 ,30, 30);
    
    [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
    
    _sendButton.titleLabel.font=[UIFont systemFontOfSize:14];
    [_sendButton setTitleColor:JZJLABELCOLOR forState:UIControlStateNormal];
    
    [_sendButton setTitle:@"发送" forState:UIControlStateHighlighted];
    
    [_sendButton addTarget:self action:@selector(sender:) forControlEvents:UIControlEventTouchUpInside];
    
    [itemts addObject:_sendButton];
    [_toolBar insertSubview:_sendButton atIndex:1];
    
    _sendButton.enabled=NO;
    _toolBar.backgroundColor=JZJLABELCOLOR;

    
    _toolBar.userInteractionEnabled=YES;
    
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    _tableView.delegate=self;
    _tableView.dataSource=self;
    
    [self.view addSubview:_tableView];
    [self.view addSubview:_toolBar];

    
//    UITapGestureRecognizer* tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
//    [_tableView addGestureRecognizer:tap];

    
    
    WS(weakSelf)
    
    //添加下拉刷新
    [_tableView addLegendHeaderWithRefreshingBlock:^{// 每次下拉都会产生效果  所以需要一次操作来停止效果
        if (!weakSelf.isLoad) {
            //开始数据请求
            _number=0;
            weakSelf.isLoad=!weakSelf.isLoad;
            
            
            if (_segmentedControl.selectedSegmentIndex==0) {
                
                [weakSelf loadLatestData];
                

                
            }else{
                
            [weakSelf loadHotData];
                
            }
        }
        else
        {
            [weakSelf.tableView.header endRefreshing];//如果正在运行 的时候拉一下会进入else但是 会产生效果   需要停止这个效果 每次下拉都会产生效果  所以需要一次操作来停止效果
            
        }
    }];
    
    
    
    //添加上拉加载
    [_tableView addLegendFooterWithRefreshingBlock:^{
        
        if (!weakSelf.isLoad)//如果没有加载为真 进入方法
        {
            _number=_number+20;
            weakSelf.isLoad=!weakSelf.isLoad;//加载状态
            
            if (_segmentedControl.selectedSegmentIndex==0) {
                
                
                [weakSelf loadLatestData];
                
                
            }else{
                [weakSelf loadHotData];
                
            }
            
//            JZJLog(@"_number%zd",_number);
            
        }else{//异步请求执行完毕之后isLoad才会变成NO 否则再次下拉会一直执行这个方法
            [weakSelf.tableView.footer endRefreshing];
            
        }
        
        
    }];
    

    

    
}


//退出模态视图
- (void)dismiss:(UIButton*)sender
{

    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark --返回按钮点击触发方法
- (void)back:(UIBarButtonItem*)sender
{

    [self.navigationController popViewControllerAnimated:YES];


}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

    
}

- (void)sender:(UIButton*)sender
{

//http://api.kuaikanmanhua.com/v1/comics/5171/comments   content  1
//    NSString* content=_textView.text;
    
    NSUserDefaults* userdefault=[NSUserDefaults standardUserDefaults];
    
    
    
    if ([userdefault boolForKey:ISLAND]==NO) {
        
        
            LandController* vc=[[LandController alloc]init];
            
        
        [self presentViewController:vc animated:YES completion:nil];
        
        
        
    
        
    }
    
    [_textView endEditing:YES];

    [DownLoad sendLatestCommentWithID:_model.id andContent:_textView.text andBlock:^(NSDictionary* dic, NSError *error) {
        
        
        
        if([dic[@"message"] isEqualToString:@"OK"])
        {
            
            
            
            
            [self loadLatestData];
            
            [_tableView reloadData];
      
            
        }

 
        
        
        
    }];

    _textView.text=nil;
    
//    JZJLog(@"xxx%zd,%@,%@",_segmentedControl.selectedSegmentIndex,[_textView.text URLEncode],_model.id);

}


- (void)keyboardWillShow:(NSNotification *)aNotification
{    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
  
    _toolBar.frame=CGRectMake(0,SCREEN_HEIGHT-keyboardRect.size.height-44, SCREEN_WIDTH, 44);
    
//    JZJLog(@"键盘高度是  %d",height);
//    JZJLog(@"键盘宽度是  %d",width);
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    
    _toolBar.frame=CGRectMake(0,SCREEN_HEIGHT-44, SCREEN_WIDTH, 44);

    
}

- (void)tap:(UITapGestureRecognizer*)tap
{

    
    if ((tap.view.tag=!tap.view.tag)) {
        
        _tableView.frame=self.view.frame;
        self.toolBar.hidden=YES;
        
        
    }
    else{
    
        _tableView.frame=CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);

        
        self.navigationController.navigationBar.hidden=NO;
        self.toolBar.hidden=NO;
        
    
    }



}

#pragma mark --UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{


    CommentCell *cell = (CommentCell*)[self tableView:_tableView cellForRowAtIndexPath:indexPath];
    
    return cell.frame.size.height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentCell* cell=[tableView dequeueReusableCellWithIdentifier:@"ID"];
    
    if (!cell) {
    
        cell=[[NSBundle mainBundle]loadNibNamed:@"CommentCell" owner:nil options:nil][0];
        cell.delegate=self;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;

    }
    
    //刷新
    
    Model* model=_dataArray[indexPath.row];
    [cell refreshWithModel:model WithIndexPath:indexPath];
    
    
    
    return cell;

    
}







#pragma mark --UITableViewDelegate


//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//
//    return 100;
//
//
//
//
//}

#pragma mark --点击时触发的方法

- (void)segmentControlValueChanged:(UISegmentedControl*)control{
    /**
     *  点击的是哪一个按钮
     */
//    NSInteger index = control.selectedSegmentIndex;
//

    
    switch (control.selectedSegmentIndex) {
        case 0:
            
        {
        
            [self loadLatestData];
            
            
            
        }
            break;
        case 1:
            
        {
            
            
            [self loadHotData];

        
        }
            break;

    }

}


- (void)textViewDidBeginEditing:(UITextView *)textView {
    

    _sendButton.enabled=YES;
    

    
    UITapGestureRecognizer* tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(keyBoardEn)];
    
    
    [_tableView addGestureRecognizer:tap];
    
    
if ([textView.text isEqualToString:@"吐槽神马的尽管来"]) {
    
    textView.text = @"";
    
}

}
- (void)keyBoardEn{


    [_textView endEditing:YES];
    
//    JZJLog(@"xx");



}

//3.在结束编辑的代理方法中进行如下操作

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    
    
    
    _tableView.backgroundColor=[UIColor clearColor];
    
    self.view.alpha=1.0;
    
    
    
    if (textView.text.length<1) {
        
        textView.text =@"吐槽神马的尽管来";
        
    }
    

    _sendButton.enabled=NO;
    
    [textView endEditing:YES];
    
}




@end
